﻿#region header

//  ***************************************************************************
// *                                LICENSE
//  ***************************************************************************
//  * "Haplous" .NET Simple 2D Game Framework
//  * 
//  * Copyright © Jonathan Evans 2014-2014
//  * 
//  * This program is free software; you can redistribute it and/or
//  * modify it under the terms of the GNU General Public License
//  * as published by the Free Software Foundation; either version 2
//  * of the License, or (at your option) any later version.
//  * 
//  * This program is distributed in the hope that it will be useful,
//  * but WITHOUT ANY WARRANTY; without even the implied warranty of
//  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  * GNU General Public License for more details.
//  * 
//  * You should have received a copy of the GNU General Public License
//  * along with this program; if not, write to the Free Software
//  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//  * 
//  ***************************************************************************
//  * 
//  * Contact: opencollar@googlemail.com
//  * 
//  * Website: http://haplous.codeplex.com/
//  *
//  * NuGet:   http://www.nuget.org/packages/haplous/
//  *
//  * File:    Haplous/Haplous/TimeCue.cs
//  *
//  ***************************************************************************

#endregion

using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;

using Haplous.Core;
using Haplous.Properties;

using JetBrains.Annotations;

namespace Haplous
{
    /// <summary>
    ///     A simple time-based Cue. This class cannot be inherited.
    /// </summary>
    [DebuggerDisplay("Cue: Name={Name}; Interval: {_interval}")]
    public sealed class TimeCue : Cue
    {
        /// <summary>
        ///     The minimum period of time between each tick.
        /// </summary>
        private readonly TimeSpan _interval;

        /// <summary>
        ///     The timer that fires the events used to trigger ticks.
        /// </summary>
        [NotNull]
        private readonly Timer _timer;

        /// <summary>
        ///     Initializes a new instance of the <see cref="ElementBase" /> class.
        /// </summary>
        /// <param name="game">
        ///     The game to which the class belongs.  The <paramref name="game" /> must not be
        ///     <see langword="null" />.
        /// </param>
        /// <param name="name">
        ///     The unique name that can be used to identify this object.  The <paramref name="name" /> must not be
        ///     <see langword="null" />, empty or all whitespace.
        /// </param>
        /// <param name="interval">
        ///     The minimum period of time between each tick.  The value of <paramref name="interval" /> must be
        ///     greater than 'TimeSpan.MinValue'.
        /// </param>
        public TimeCue([NotNull] Game game, [NotNull] string name, TimeSpan interval) : base(game, name)
        {
            if(interval == TimeSpan.MinValue)
                throw new ArgumentOutOfRangeException("interval", interval, Resources.Error_IntervalMustBeNonZero);

            _interval = interval;
            _timer = new Timer(OnTimer, null, -1, -1);
        }

        /// <summary>
        ///     Called when the timer fires.
        /// </summary>
        /// <param name="state">The state.</param>
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void OnTimer([CanBeNull] object state)
        {
            try
            {
                OnTick();
            }
            catch(Exception ex)
            {
                ErrorManager.OnUnhandledException(ex);
            }
        }

        /// <summary>
        ///     Called when the Cue must start issuing ticks.
        /// </summary>
        protected override void OnStart()
        {
            _timer.Change(_interval, _interval);
        }

        /// <summary>
        ///     Called when the Cue must stop issuing ticks.
        /// </summary>
        protected override void OnStop()
        {
            _timer.Change(-1, -1);
        }

        /// <summary>
        ///     Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing">
        ///     <see langword="true" /> to release both managed and unmanaged resources;
        ///     <see langword="false" /> to release only unmanaged resources.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            if(disposing)
            {
                _timer.Change(-1, -1);
                _timer.Dispose();
            }

            base.Dispose(disposing);
        }
    }
}